/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: syyyy
 * Date: 2025-09-10
 * Time: 9:09
 */
public class BinarySearchTree {
    public static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val){
            this.val=val;
        }
    }

    public TreeNode root;

    public TreeNode search(int key){
        TreeNode cur=root;
        while(cur != null){
            if(cur.val == key){
                return cur;
            }else if (cur.val > key){
                cur=cur.left;
            }else {
                cur=cur.right;
            }
        }
        return null;
    }

    public void insert(int key){
        TreeNode node=new TreeNode(key);
        TreeNode cur=root;
        TreeNode parent=null;
        if(root == null){
            root=node;
            return;
        }
        while(cur != null){
            if(cur.val == key){
                return;
            }else if (cur.val > key){
                parent=cur;
                cur=cur.left;
            }else {
                parent=cur;
                cur=cur.right;
            }
        }
        if(parent.val > key){
            parent.left=node;
        } else if (parent.val < key) {
            parent.right=node;
        }
    }

    public void remove(int key){
        if(root == null){
            return;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur != null){
            if(cur.val == key){
                removeKey(key,cur,parent);
            }else if (cur.val > key){
                parent=cur;
                cur=cur.left;
            }else {
                parent=cur;
                cur=cur.right;
            }
        }
        return;
    }

    private void removeKey(int key, TreeNode cur, TreeNode parent) {
        if (cur.left==null){
            if(cur==root) {
                root = cur.right;
            }
            else if (parent.left==cur) {
                parent.left = cur.right;
            }
            else {
                parent.right = cur.right;
            }
        } else if (cur.right==null) {
            if(cur==root){
                root=cur.left;
            } else if (parent.left==cur) {
                parent.left=cur.left;
            }else {
                parent.right=cur.left;
            }
        }else {
            TreeNode targetParent=cur;
            TreeNode target=cur.right;
            while(target.left!=null){
                targetParent=target;
                target=target.left;
            }
            cur.val=target.val;
            if(targetParent.left==target){
                targetParent.left=target.right;
            }else {
                targetParent.right=target.right;
            }
        }
    }
}
